<template>
  <div>
    <div class="scoreClass">
      <label>本关题目：{{roundScore}}/{{problemNumbers}}</label>
    </div>
    <div class="deadline">
      <h2>剩余时间：<span style="color:red">{{time}}</span>s</h2>
    </div>
    <img src="/static/images/voice_run.png" class="bgmImg" v-if="isPlayMusic" @click="changeMusicStatus">
    <img src="/static/images/voice_stop.png" class="bgmImg" v-if="!isPlayMusic" @click="changeMusicStatus">
    <div>
      <span>{{problem}}</span>
    </div>
    <div v-for="i in selectNums">
      <button @click="judge(i-1)"><span class="selectID">{{choice[i]}}</span></button>
    </div>
    <div class="weui-btn-area">
      <span>{{answer}}</span>
      <mp-toast :type="errorType" v-model="showToast" :content="content" :duration="duration"></mp-toast>
      <mp-toast :type="successType" v-model="showSuccessToast" :content="success" :duration="duration"></mp-toast>
    </div>
  </div>
</template>

<script>
  import mpToast from 'mpvue-weui/src/toast'
  import {queryPapersById, addErrorProblem} from '../../util/api'
  export default {
    components: {
      mpToast
    },
    data () {
      return {
        errorType: 'error',
        successType: 'success',
        content: '闯关失败',
        success: '闯关成功',
        duration: 1500,
        showToast: false,
        showSuccessToast: false,
        time: 0,
        roundScore: 0,
        problemNumbers: 5,
        problem: '',
        choice: [0, 0, 0, 0],
        selectNums: 4,
        answer: '',
        charArray: ['a', 'b', 'c', 'd', 'e'],
        problems: [],
        problemId: '',
        backgroundAudioManager: '',
        isPlayMusic: false,
        intervalNum: 0
      }
    },
    methods: {
      countDown () {
        if (this.time > 0) {
          this.time--
        } else {
          this.showToast = true
          clearInterval(this.intervalNum)
          setTimeout(function () {
            wx.redirectTo({
              url: '../user-roundbtn/main'
            })
          }, this.duration)
        }
      },
      judge (i) {
        const ans = this.answer.toLowerCase()
        if (this.charArray[i] === ans) {
          this.nextProblems()
        } else {
          this.showToast = true
          clearInterval(this.intervalNum)
          addErrorProblem(this.problemId, this.$store.state.openid)
            .then((response) => {
              console.log(response)
            })
            .catch((error) => {
              console.log(error)
            })
          setTimeout(function () {
            wx.redirectTo({
              url: '../user-roundbtn/main'
            })
          }, this.duration)
        }
      },
      nextProblems () {
        // 判断是否是最后一题
        if (this.roundScore < this.problemNumbers - 1) {
          this.roundScore = this.roundScore + 1
          this.time = 20
          this.choice[0] = this.problems[this.roundScore].choice_A
          this.choice[1] = this.problems[this.roundScore].choice_B
          this.choice[2] = this.problems[this.roundScore].choice_C
          this.choice[3] = this.problems[this.roundScore].choice_D
          this.problem = this.problems[this.roundScore].text
          this.answer = this.problems[this.roundScore].answer
          this.problemId = this.problems.problems[this.roundScore].problemId
        } else { // 完成闯关
          this.$fly.put(this.$store.state.URL + '/studygo/addScore', {
            username: this.$store.state.openid,
            score: 10
          })
            .then((response) => {
              console.log(response)
            })
            .catch((error) => {
              console.log(error)
            })
          if (this.$store.state.roundSelectNum === this.$store.state.myNumsOfRound) {
            this.$fly.put(this.$store.state.URL + '/studygo/record/saveRecord', {
              userId: this.$store.state.userId,
              gatewayId: this.$store.state.roundSelectedDate.id,
              grade: this.$store.state.userGrade,
              subject: this.$store.state.userSubject
            })
              .then((response) => {
                console.log(response)
              })
              .catch((error) => {
                console.log(error)
              })
          }
          this.showSuccessToast = true
          clearInterval(this.intervalNum)
          setTimeout(function () {
            wx.redirectTo({
              url: '../user-roundbtn/main'
            })
          }, this.duration)
        }
      },
      getBackgroundMusic () {
        const backgroundAudioManager = wx.getBackgroundAudioManager()
        backgroundAudioManager.title = 'bgm'
        // 设置了 src 之后会自动播放
        backgroundAudioManager.src = 'http://ws.stream.qqmusic.qq.com/C400003vtICn1FQNTF.m4a?guid=9273422998&vkey=2DDB2E573887C539A24A8E933999D08FC772FD96F5A84B66BAD8BD362A475C8A5B6E1FF4BBB7DF9E8FC3E021EA7D4C69A2F8EE6B7CAC2DE6&uin=0&fromtag=66'
        this.backgroundAudioManager = backgroundAudioManager
        this.isPlayMusic = true
      },
      changeMusicStatus () {
        this.isPlayMusic = !this.isPlayMusic
        if (this.isPlayMusic) {
          this.backgroundAudioManager.play()
        } else {
          this.backgroundAudioManager.pause()
        }
      }
    },
    beforeMount () {
      this.getBackgroundMusic()
    },
    mounted () {
      queryPapersById(this.$store.state.roundSelectedDate.paperId.toString(), true)
        .then(response => {
          console.log(response.data)
          this.problemNumbers = response.data.results[0].problems.length
          this.problems = response.data.results[0].problems
          this.choice[0] = response.data.results[0].problems[0].choice_A
          this.choice[1] = response.data.results[0].problems[0].choice_B
          this.choice[2] = response.data.results[0].problems[0].choice_C
          this.choice[3] = response.data.results[0].problems[0].choice_D
          this.problem = response.data.results[0].problems[0].text
          this.answer = response.data.results[0].problems[0].answer
          this.problemId = response.data.results[0].problems[0].problemId
        })
        .catch(function (error) {
          console.log(error)
        })
      let THIS = this
      THIS.time = 20
      this.intervalNum = setInterval(THIS.countDown, 1000)
    },
    onShow () {
      this.roundScore = 0
    },
    onUnload () {
      this.backgroundAudioManager.stop()
      this.isPlayMusic = false
      clearInterval(this.intervalNum)
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  page {
    background-image: url();
  }
  .bgmImg{
    height: 50rpx;
    width: 50rpx;
  }
  .problem {
    height: 40px;
  }

  .scoreClass {
    height: 50px;
    background: dodgerblue;
    font-family: "华文楷体";
    font-style: italic;
  }

  .deadline {
    height: 50px;
    margin-left: 35%;
    font-family: "华文楷体";
  }

  .selectID {
    float: left;
    font-family: "华文楷体";
  }

  ._touch {
    padding-top: 48px;
  }

  .round_box {
    position: relative;
    width: 54%;
    padding-top: 54%;
    margin: 0 auto;
    background-size: auto 100%;
    background-position: center top;
    background-repeat: no-repeat;
  }

  .round_right {
    width: 8%;
    height: 27%;
    position: absolute;
    left: 46%;
    top: 23%;
    transform-origin: 50% 100%;
    -webkit-transform-origin: 50% 100%;
    z-index: 2;
  }

  .round_info {
    background: linear-gradient(#858585, #b3b3b3);
    background: -webkit-gradient(#858585, #b3b3b3);
    background: -moz-linear-gradient(#858585, #b3b3b3);
    width: 100%;
    padding-top: 100%;
    border-radius: 100%;
  }

  .round_num {
    display: inline-block;
    position: absolute;
    z-index: 1;
    text-align: center;
    width: 30%;
    top: 38%;
    left: 35%;
    font-size: 2.4em;
    font-weight: 900;
    background: linear-gradient(#b0b0b0, #c8c8c8);
    background: -webkit-gradient(#b0b0b0, #c8c8c8);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    text-fill-color: transparent;
  }
</style>
